import 'package:cbec_app/components/base/base_customize_segmented_control.dart';
import 'package:cbec_app/components/base/base_image.dart';
import 'package:cbec_app/components/base/base_interactive.dart';
import 'package:cbec_app/components/common/common_style.dart';
import 'package:cbec_app/components/common/count_down_timer.dart';
import 'package:cbec_app/components/common/not_found.dart';
import 'package:cbec_app/pages/goods/controller/kill_sales_ctr.dart';
import 'package:cbec_app/pages/goods/entity/activity_item_entity.dart';
import 'package:cbec_app/routes/routes.dart';
import 'package:cbec_app/utils/Tools.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import '../binding/goods_detail_binding.dart';
import 'goods_detail_page.dart';

//秒杀页面
class KillSalesPage extends GetView<KillSalesController> {
  const KillSalesPage({super.key});

  List<Widget> _createItemWidgets() {
    final KillSalesController controller = Get.find<KillSalesController>();
    List<Widget> widgetArr = [];
    for (int i = 0; i < controller.itemList.length; i++) {
      ActivityItemEntity item = controller.itemList[i];
      int selectIndex = controller.selected;
      if (i == 0) {
        widgetArr.add(
          Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.start,
            // mainAxisSize: MainAxisSize.max,
            children: [
              Container(
                width: 200.h,
                padding: const EdgeInsets.only(left: 10),
                child: CountDownTimer(
                  timeStamp: DateTime.parse(item.endtime ?? '').millisecondsSinceEpoch,
                  timeStyle: TimeStyle.hhmmss,
                  countDownStyle: CountDownStyle.box,
                  boxBackgroundColor: Tools.fromHex("#000000"),
                  colonColor: Tools.fromHex("#000000"),
                  style: setTextStyle(
                    12,
                    FontWeight.w400,
                    Tools.fromHex('#FFFFFF'),
                  ),
                  callback: () {},
                ),
              ),
              const SizedBox(
                height: 5,
              ),
              Container(
                padding: const EdgeInsets.only(left: 20),
                width: double.infinity,
                // alignment: Alignment.center,
                child: Text(
                  '正在抢购',
                  style: TextStyle(
                    color: selectIndex == i ? Tools.fromHex('#F83F2D') : Tools.fromHex('#FFFFFF'),
                  ),
                ),
              ),
            ],
          ),
        );
      } else {
        widgetArr.add(
          Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(
                item.begintime ?? '',
                style: TextStyle(
                  color: selectIndex == i ? Tools.fromHex('#F83F2D') : Tools.fromHex('#FFFFFF'),
                ),
              ),
              const SizedBox(
                height: 3,
              ),
              Text(
                '即将开始',
                style: TextStyle(color: selectIndex == i ? Tools.fromHex('#F83F2D') : Tools.fromHex('#FFFFFF'), fontWeight: FontWeight.w500, fontSize: 12),
              ),
            ],
          ),
        );
      }
    }
    return widgetArr;
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<KillSalesController>(builder: (controller) {
      return Scaffold(
        extendBodyBehindAppBar: true, // 允许 body 从 AppBar 顶部开始布局
        appBar: AppBar(
          backgroundColor: Colors.transparent, // 设置透明
          leading: IconButton(
            icon: const Icon(
              Icons.arrow_back,
              color: Colors.black,
            ),
            onPressed: () {
              Navigator.pop(context);
            },
          ),
        ),
        body: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 自适应高度的图片
            SizedBox(
              width: double.infinity,
              child: Image.asset("assets/images/ms_bg.png", fit: BoxFit.fitWidth),
            ),

            // 分段控件
            SizedBox(
              height: 60,
              child: BaseCustomizeSegmentedControl(
                items: _createItemWidgets(),
                selectedIndex: controller.selected,
                onChanged: (index) {
                  controller.change(index);
                },
              ),
            ),

            // 列表
            Expanded(
              child: controller.goodsList.isNotEmpty
                  ? Tools.getPullRefresh(
                      enablePullDown: true,
                      enablePullUp: true,
                      refreshController: controller.baseRefreshCtr,
                      onRefresh: controller.onPageRefresh,
                      onLoading: controller.onPageLoading,
                      child: controller.style == 1
                          ? ListView.builder(
                              controller: controller.scrollController,
                              padding: EdgeInsets.zero, // 移除默认的内边距
                              itemCount: controller.goodsList.length,
                              itemBuilder: (context, index) {
                                final Map item = controller.goodsList[index];
                                return KillSalesListItem1(item: item);
                              },
                            )
                          : GridView.count(
                              padding: EdgeInsets.zero,
                              childAspectRatio: 2 / 3,
                              mainAxisSpacing: 10.w,
                              shrinkWrap: true,
                              crossAxisCount: 3,
                              children: List.generate(controller.goodsList.length, (index) {
                                final Map item = controller.goodsList[index];
                                return KillSalesListItem2(item: item);
                              }),
                            ),
                    )
                  : const NotFound(),
            ),
          ],
        ),
      );
    });
  }
}

class KillSalesListItem2 extends StatelessWidget {
  final Map item;

  const KillSalesListItem2({
    super.key,
    required this.item,
  });

  @override
  Widget build(BuildContext context) {
    return BaseInteractive(
      onClick: () {
        final id = item['goodsId'];
        Get.to(
          () => GoodsDetailPage(flag: id), // 使用函数懒加载页面实例
          routeName: '${Routes.goodsDetail}?unique=${DateTime.now().millisecondsSinceEpoch}',
          arguments: {"id": id}, // 传递其它参数
          binding: GoodsDetailBinding(flag: id), // 将 tag 参数传递给绑定类
        );
      },
      childWidget: Container(
        width: 100.w,
        color: Colors.white,
        child: Column(
          children: [
            BaseImage(url: item['mainImage'], width: 100, height: 100),
            Container(
              alignment: Alignment.center,
              width: 100.w,
              decoration: BoxDecoration(
                color: Tools.fromHex("#FDD9D7"),
                borderRadius: const BorderRadius.only(
                  bottomLeft: Radius.circular(5.0),
                  bottomRight: Radius.circular(5.0),
                ),
              ),
              child: Text("已抢${item['soldRatio'].toString()}%", style: setTextStyle(12, FontWeight.w300, Tools.fromHex("#FF3739"))),
            ),
            SizedBox(height: 4.h),
            Text(item['commodityName'], style: setTextStyle(12, FontWeight.w400, Tools.fromHex("#3D3D3D"))),
            SizedBox(height: 5.w),
            SizedBox(
              width: 100.w,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Row(
                    children: [
                      Text(item['soldRatio'].toString().split(".")[0], style: setTextStyle(15, FontWeight.w700, Tools.fromHex("#F83F2D"))),
                      Text(item['soldRatio'].toString().split(".")[1], style: setTextStyle(10, FontWeight.w400, Tools.fromHex("#F83F2D"))),
                    ],
                  ),
                  BaseInteractive(
                    onClick: () {
                      final id = item['goodsId'];
                      Get.to(
                        () => GoodsDetailPage(flag: id), // 使用函数懒加载页面实例
                        routeName: '${Routes.goodsDetail}?unique=${DateTime.now().millisecondsSinceEpoch}',
                        arguments: {"id": id}, // 传递其它参数
                        binding: GoodsDetailBinding(flag: id), // 将 tag 参数传递给绑定类
                      );
                    },
                    childWidget: BaseImage(url: "kill_button_2.png", width: 25, height: 20),
                  )
                ],
              ),
            )
          ],
        ),
      ),
    );
  }
}

class KillSalesListItem1 extends StatelessWidget {
  final Map item;

  const KillSalesListItem1({
    super.key,
    required this.item,
  });

  @override
  Widget build(BuildContext context) {
    return BaseInteractive(
      onClick: () {
        final id = item['goodsId'];
        Get.to(
          () => GoodsDetailPage(flag: id), // 使用函数懒加载页面实例
          routeName: '${Routes.goodsDetail}?unique=${DateTime.now().millisecondsSinceEpoch}',
          arguments: {"id": id}, // 传递其它参数
          binding: GoodsDetailBinding(flag: id), // 将 tag 参数传递给绑定类
        );
      },
      childWidget: Container(
        decoration: border_radis(Colors.white),
        margin: EdgeInsets.only(bottom: 10.w),
        child: Row(
          children: [
            Padding(
              padding: const EdgeInsets.all(10.0),
              child: ClipRRect(
                borderRadius: BorderRadius.circular(8),
                child: BaseImage(url: item['mainImage'], width: 116, height: 116),
              ),
            ),
            SizedBox(width: 10.w),
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                SizedBox(height: 8.h),
                SizedBox(
                  width: 220.w,
                  child: Text(item['commodityName'], style: setTextStyle(14, FontWeight.w500, Tools.fromHex("#333333")), overflow: TextOverflow.ellipsis, maxLines: 1),
                ),
                SizedBox(height: 4.h),
                Row(
                  children: [
                    Container(
                      decoration: border_radis(Colors.white, borderColor: Tools.fromHex("#E7A786"), radiusValue: 5),
                      padding: EdgeInsets.fromLTRB(4.w, 2.w, 4.w, 2.w),
                      child: Text("剩余${item['storage']}件", style: setTextStyle(10, FontWeight.w300, Tools.fromHex("#E7A786"))),
                    ),
                    Container(
                        margin: EdgeInsets.only(left: 8.w),
                        decoration: border_radis(Tools.fromHex("#FFEEEE"), radiusValue: 5),
                        padding: EdgeInsets.fromLTRB(4.w, 2.w, 4.w, 2.w),
                        child: Text(
                            item['commodityType'] == 0
                                ? "一般贸易"
                                : item['commodityType'] == 1
                                    ? "保税"
                                    : item['commodityType'] == 2
                                        ? "海外直邮"
                                        : "",
                            style: setTextStyle(10, FontWeight.w300, Tools.fromHex("#F83F2D"))))
                  ],
                ),
                SizedBox(height: 10.h),
                SizedBox(
                  width: 150.w,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.end,
                    children: [
                      Row(
                        children: [Text("￥", style: setTextStyle(10, FontWeight.w300, Tools.fromHex("#F83F2D"))), Text(item['seckillPrice'].toString(), style: setTextStyle(18, FontWeight.w700, Tools.fromHex("#F83F2D")))],
                      ),
                      const SizedBox(width: 5),
                      Text('日常价¥${item['price'].toString()}', style: setTextStyle(10, FontWeight.w300, Tools.fromHex("#999999")))
                    ],
                  ),
                ),
                SizedBox(height: 4.h),
                Container(
                  alignment: Alignment.centerLeft,
                  decoration: const BoxDecoration(
                    image: DecorationImage(
                      image: AssetImage('assets/images/kill_button.png'), // 替换为你的背景图路径
                      fit: BoxFit.fill,
                    ),
                  ),
                  width: 206.w,
                  height: 32.h,
                  child: Row(
                    children: [
                      Container(
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(5.0), // 设置圆角的半径
                        ),
                        clipBehavior: Clip.hardEdge,
                        margin: EdgeInsets.only(left: 5.w, right: 5.w),
                        width: 80.w,
                        child: LinearProgressIndicator(
                          backgroundColor: Tools.fromHex("#FF9B97"), // 背景颜色
                          valueColor: AlwaysStoppedAnimation<Color>(Tools.fromHex("#FF4E42")), // 进度条颜色
                          value: item['soldRatio'] / 100, // 进度值，0.0表示无进度，1.0表示完全完成
                          minHeight: 10.0, // 最小高度
                        ),
                      ),
                      Text(
                        "已抢${item['soldRatio'].toString()}%",
                        style: setTextStyle(10, FontWeight.w300, Tools.fromHex("#F83F2D")),
                      )
                    ],
                  ),
                ),
                SizedBox(height: 7.h),
              ],
            )
          ],
        ),
      ),
    );
  }
}
